package com.site.config;

import com.common.encryt.MD5;
import com.common.exception.BusinessException;
import com.common.util.SecreUtil;
import com.google.common.base.Strings;
import com.site.model.User;
import com.site.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
* Created by robin on 2016/2/19.
* 用户验证
*/
public class DbRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

//    @Autowired
//    RoleService roleService;
//    @Autowired
//    PermissionService permissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userid = (String) principalCollection.getPrimaryPrincipal();
//        User user=userService.selectById(userid);
        if (!Strings.isNullOrEmpty(userid)) {
            SimpleAuthorizationInfo authenticationInfo = new SimpleAuthorizationInfo();
//            authenticationInfo.setRoles(roleService.convert(roleService.selectByUser(user)));
//            authenticationInfo.setStringPermissions(permissionService.convert(permissionService.selectAllByUser(user)));
            return authenticationInfo;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = String.valueOf(usernamePasswordToken.getUsername());
        User user = userService.selectByName(username);
        AuthenticationInfo authenticationInfo = null;
        if (null != user) {
            String password = new String(usernamePasswordToken.getPassword());
            if (password.equals(user.getUserPassword())) {
                Map map=new HashMap<>();
                map.put("nickname",user.getUserNickname());
                map.put("name",user.getUserName());
                map.put("password",user.getUserPassword());
                SecreUtil.putSessionValue(SecreUtil.SessionAtrr.USERMAP,map);
                SecreUtil.putSessionValue(SecreUtil.SessionAtrr.SYSUSERNAME,user.getUserName());
                authenticationInfo = new SimpleAuthenticationInfo(user.getUserId(), user.getUserPassword(), getName());
            }else {
                throw new AuthenticationException("用户名和密码不匹配");
            }
        }
        return authenticationInfo;
    }


}
